<template>
    <view class="pg">
        <wd-form ref="form" :model="model">
            <wd-cell-group border>
                <wd-input
                    size="large"
                    label="名称"
                    label-width="100px"
                    prop="name"
                    clearable
                    v-model="model.name"
                    placeholder="场地名称"
                    :rules="[{ required: true, message: '请填写场地名称' }]"
                />
                <wd-input
                    size="large"
                    label="电话"
                    label-width="100px"
                    prop="phone"
                    clearable
                    v-model="model.phone"
                    placeholder="管理员电话"
                    :rules="[{ required: true, pattern: /\d{11}/, message: '请正确填写管理员电话' }]"
                />
                <wd-picker
                    value-key="id"
                    label-key="name"
                    size="large"
                    label="场地类别"
                    placeholder="请选择场地类别"
                    label-width="100px"
                    prop="category"
                    v-model="model.category"
                    :columns="categoryList"
                    :rules="[{ required: true, message: '请选择场地类别' }]"
                />
                <wd-col-picker
                    value-key="id"
                    label-key="name"
                    size="large"
                    label="选择地址"
                    title="选择地址"
                    prop="region"
                    v-model="model.region"
                    :columns="regionList"
                    :column-change="regionChange"
                    @confirm="region_confirm"
                    :rules="[{ required: true, message: '请选择地址' }]"
                ></wd-col-picker>
                <wd-input size="large" label="备注/说明" label-width="100px" clearable v-model="model.remark" placeholder="非必填" />
                <wd-button size="large" type="primary" custom-class="w-700 m-10-0-10-25" @click="handleSubmit">提交</wd-button>
            </wd-cell-group>
        </wd-form>
    </view>
</template>

<script setup>
    import { reactive, ref } from 'vue';
    import { onShow, onLoad } from '@dcloudio/uni-app';
    import { api_region_save, api_region_getDictRegion3 } from '@/api/region.js';
    import { api_regionCategory_list } from '@/api/regionCategory.js';

    const form = ref(null); //表单

    // 模型数据
    const model = reactive({
        name: '',
        phone: '',
        category: '',
        region: [],
        remark: ''
    });

    // 类型选择器列表
    const categoryList = ref([]);

    // 地区选择器列表 需要两个，regionList是[regionPicker] 别问我为什么
    const regionList = ref([]);
    const regionPicker = ref([]);

    onLoad(async () => {
        //加载场地类别
        try {
            let res = await api_regionCategory_list({ pageCut: false });
            categoryList.value = res.data;
        } catch (error) {
            uni.showToast({
                title: error.msg,
                icon: 'none'
            });
        }

        //加载地址（省市区）
        try {
            let res = await api_region_getDictRegion3();
            regionList.value = [res.data];
            regionPicker.value = res.data;
            console.log('地址列表', res);
        } catch (error) {
            uni.showToast({
                title: error.msg,
                icon: 'none'
            });
        }
    });

    //选择地区函数
    const regionChange = ({ selectedItem, resolve, finish }) => {
        const regionData = findChildrenByCode(regionPicker.value, selectedItem.id);
        console.log('地区', regionPicker.value, selectedItem.id);
        if (regionData && regionData.length) {
            resolve(regionData);
        } else {
            finish();
        }
    };

    // 地区选择完毕函数
    const region_confirm = ({ value }) => {
        console.log('选择的地区id数组', value);
    };

    // 提交表单
    const handleSubmit = async () => {
        // 执行表单验证
        try {
            let { valid, errors } = await form.value.validate();

            // 表单验证通过
            if (valid) {
                uni.showModal({
                    //确认提示框
                    title: '是否提交',
                    success: async (res) => {
                        if (res.confirm) {
                            // 序列化region数组
                            let formattRegion = JSON.stringify(model.region);
                            let submitForm = {
                                ...model,
                                region: formattRegion
                            };
                            // 访问添加接口;
                            try {
                                let res = await api_region_save(submitForm);
                                uni.showToast({
                                    title: res.msg,
                                    icon: 'success',
                                    success: () => {
                                        uni.navigateBack();
                                    }
                                });
                            } catch (error) {
                                ni.showToast({
                                    title: error.msg,
                                    icon: 'none'
                                });
                            }
                        }
                    }
                });

                console.log(model);
            } else {
                console.log('校验失败', errors);
            }
        } catch (error) {
            // 表单验证失败或发生其他错误
            console.error('错误', error);
        }
    };
</script>

<style lang="scss" scoped>
    /* 你可以在这里添加样式 */
</style>
